import { API_BASE_URL } from "@/constant";
import { ApiResp } from "@/types/response";
import { UserProfile } from "@/types/user";
import axios, { AxiosResponse } from "axios";
import { HttpStatusCode } from "axios"; 



const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});


// 请求拦截器，添加认证token
apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);



// 响应拦截器，处理全局错误
apiClient.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    return response;
  },
  (error) => {

    if (error.response && error.response.status === HttpStatusCode.Unauthorized) {
      storageService.clearAuth();
    }
    return Promise.reject(error);
  }
);



// 本地存储服务
const storageService = {
  setToken: (token: string) => {
    localStorage.setItem('token', token);
  },
  getToken: () => {
    return localStorage.getItem('token');
  },
  setUser: (user: UserProfile) => {
    localStorage.setItem('user', JSON.stringify(user));
  },
  getUser: (): UserProfile | null => {
    const user = localStorage.getItem('user');
    return user ? JSON.parse(user) : null;
  },
  clearAuth: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
  }
};



 const extractDataFromResponse = <T>(response: AxiosResponse<ApiResp<T>>): T | null => {
    if (response.data.code === 0 && "data" in response.data) {
      return response.data.data;
    } else if (response.data.code !== 0 && "message" in response.data) {
      console.error("Error:", response.data.message);
      return null;
    }
    return null;
  }

export { apiClient, storageService, extractDataFromResponse };
